/*
 * @(#)CommonIndexTag.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.dms.taglib;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspException;

import com.dcivision.dms.DmsOperationConstant;
import com.dcivision.dms.bean.DmsDefaultProfileSetting;
import com.dcivision.dms.core.DocumentRetrievalManager;
import com.dcivision.framework.ApplicationException;
import com.dcivision.framework.GlobalConstant;
import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.SystemParameterConstant;
import com.dcivision.framework.SystemParameterFactory;
import com.dcivision.framework.TextUtility;
import com.dcivision.framework.Utility;
import com.dcivision.framework.taglib.html.FormTag;

/**
 * Custom tag that iterates the document common index. The index list can be
 * passed in using the <code>name</code> attribute, and the attribute name of
 * each iteration object can be specified in the <code>id</code> attribute.<p>
 *
 * Below is a sample usage to list out all the common index name.<p>
 *
 * &lt;dms:commonIndex id="setting" name="DMS_DEF_PROFILE" scope="application" indexId="userDefIndex"&gt;<br>
 * &lt;dms:commonIndexName/&gt;<br>
 * &lt;/dms:commonIndex&gt;
 *
 * @author  Lun Au
 * @company DCIVision Limited
 * @date    2007-05-04
 * @version $Revision: 1.1.2.8 $
 * @see     com.dcivision.dms.taglib.CommonIndexNameTag
 */
public class CommonIndexTag extends org.apache.struts.taglib.logic.IterateTag {

  public static final String DEFAULT_PROFILE_SETTING_SCOPE = "application";

  public static final String DEFAULT_PROFILE_SETTING_INDEX = "userDefIndex";

  public static final String DEFAULT_PROFILE_SETTING_BEAN = "setting";

  public static final String DEFAULT_DOCUMENT_BEAN = "dmsDocument";

  protected String documentBean = null;
  
  private boolean includeSystemProfile = false;
  
  private boolean enableDisplayFilter = false;
  
  private boolean showProfileAsc = true;
  
  private String[] defaultSelectedDisplayIDs = null;
  
  private String[] commonSelectedDisplayIDs = null;
  
  private boolean isSkipCurrentBody = false;

  /**
   * @return the enableDisplayFilter
   */
  public boolean isEnableDisplayFilter() {
    return enableDisplayFilter;
  }

  /**
   * @param enableDisplayFilter the enableDisplayFilter to set
   */
  public void setEnableDisplayFilter(boolean enableDisplayFilter) {
    this.enableDisplayFilter = enableDisplayFilter;
  }

  /**
   * @return the showProfileAsc
   */
  protected boolean isShowProfileAsc() {
    return showProfileAsc;
  }

  /**
   * @param showProfileAsc the showProfileAsc to set
   */
  protected void setShowProfileAsc(boolean showProfileAsc) {
    this.showProfileAsc = showProfileAsc;
  }

  /**
   * @return the commonSelectedDisplayIDs
   */
  protected String[] getCommonSelectedDisplayIDs() {
    return defaultSelectedDisplayIDs;
  }

  /**
   * @param commonSelectedDisplayIDs the commonSelectedDisplayIDs to set
   */
  protected void setCommonSelectedDisplayIDs(String[] commonSelectedDisplayIDs) {
    this.defaultSelectedDisplayIDs = commonSelectedDisplayIDs;
  }

  /**
   * @return the isSkipCurrentBody
   */
  protected boolean isSkipCurrentBody() {
    return isSkipCurrentBody;
  }

  /**
   * @param isSkipCurrentBody the isSkipCurrentBody to set
   */
  protected void setSkipCurrentBody(boolean isSkipCurrentBody) {
    this.isSkipCurrentBody = isSkipCurrentBody;
  }

  /**
   * @return the systemSelectedDisplayIDs
   */
  protected String[] getSystemSelectedDisplayIDs() {
    return commonSelectedDisplayIDs;
  }

  /**
   * @param systemSelectedDisplayIDs the systemSelectedDisplayIDs to set
   */
  protected void setSystemSelectedDisplayIDs(String[] systemSelectedDisplayIDs) {
    this.commonSelectedDisplayIDs = systemSelectedDisplayIDs;
  }

  /**
   * @return the includeSystemProfile
   */
  public boolean isIncludeSystemProfile() {
    return includeSystemProfile;
  }

  /**
   * @param includeSystemProfile the includeSystemProfile to set
   */
  public void setIncludeSystemProfile(boolean includeSystemProfile) {
    this.includeSystemProfile = includeSystemProfile;
  }

  /**
   * @return the documentBean
   */
  public String getDocumentBean() {
    return documentBean;
  }

  /**
   * @param documentBean the documentBean to set
   */
  public void setDocumentBean(String documentBean) {
    this.documentBean = documentBean;
  }

  /**
   * Setup the number {@link com.dcivision.framework.SystemParameterConstant#DMS_DEFAULT_PROFILE_FIELD_COUNT})
   *   of index to be displayed,<br>
   * Setup the bean {@link org.apache.struts.taglib.logic.IterateTag#getName()} for retrieving the index
   *   template,<br>
   * Setup the bean {@link #getDocumentBean()} for retrieving the index value,<br>
   * and begin looping through the body once per common index.
   *
   * @see javax.servlet.jsp.tagext.BodyTagSupport#doStartTag()
   */
  public int doStartTag() throws JspException {
    if(Utility.isEmpty(this.getId())){
      this.setId(CommonIndexTag.DEFAULT_PROFILE_SETTING_BEAN);
    }
    if(Utility.isEmpty(this.getName())){
      this.setName(DmsOperationConstant.DMS_DEFAULT_PROFILE_SETTING);
    }
    if(Utility.isEmpty(this.getScope())){
      this.setScope(CommonIndexTag.DEFAULT_PROFILE_SETTING_SCOPE);
    }
    if(Utility.isEmpty(this.getIndexId())){
      this.setIndexId(CommonIndexTag.DEFAULT_PROFILE_SETTING_INDEX);
    }
     int totalFieldCount = Integer.parseInt(com.dcivision.framework.SystemParameterFactory.getSystemParameter(com.dcivision.framework.SystemParameterConstant.DMS_DEFAULT_PROFILE_FIELD_COUNT));
     if (includeSystemProfile) {
        totalFieldCount += 2;
      }
     if(totalFieldCount<=0) {
        return SKIP_BODY;
      }
    setLength(String.valueOf(totalFieldCount));
    if(Utility.isEmpty(this.getDocumentBean())){
      FormTag formTag = (FormTag)findAncestorWithClass(this, FormTag.class);
      this.setDocumentBean(formTag.getBeanName());
    }
    
    if (isEnableDisplayFilter() || isIncludeSystemProfile()) {      
      initProfileData();
    }

    return super.doStartTag();
  }

  /**
   * @see org.apache.struts.taglib.logic.IterateTag#doAfterBody()
   */
  public int doAfterBody() throws JspException {
    if (isEnableDisplayFilter() && isSkipCurrentBody) {
      bodyContent.clearBody();
    }
    return super.doAfterBody();
  }

  protected void initProfileData() throws JspException {
    String profileSettingStr = SystemParameterFactory.getSystemParameter(SystemParameterConstant.DMS_DEFAULT_PROFILE_FIELD_LIST);
    if (Utility.isEmpty(profileSettingStr)) {
      return;
    }
    
    if (TextUtility.splitString(profileSettingStr, "|").length < 3) {
      return;
    }
    
    if (isIncludeSystemProfile()) {
      String orderSettingStr = TextUtility.splitString(profileSettingStr, "|")[2];
      if (DmsOperationConstant.DEFAULT_PROFILE_SETTING_DESC.equals(orderSettingStr)) {
        setShowProfileAsc(false);
      } else {
        setShowProfileAsc(true);
      }
      
      initProfileList();
    }

    if (isEnableDisplayFilter()) {
      String defaultSetting = TextUtility.splitString(profileSettingStr, "|")[0];
      String commonSetting = TextUtility.splitString(profileSettingStr, "|")[1];
      
      defaultSelectedDisplayIDs = defaultSetting != null ? defaultSetting.split(",") : null;
      commonSelectedDisplayIDs = commonSetting != null ? commonSetting.split(",") : null;
    }
  }
  
  protected void initProfileList() throws JspException {
    SessionContainer sessionContainer = (SessionContainer) pageContext.getSession().getAttribute(GlobalConstant.SESSION_CONTAINER_KEY);
    Connection conn = (Connection) pageContext.getRequest().getAttribute(GlobalConstant.DB_KEY);
    DocumentRetrievalManager docRetrievalManager = new DocumentRetrievalManager(sessionContainer, conn);
    
    try {
      List defaultProfileList = docRetrievalManager.checkNSetDefaultProfileList((HttpServletRequest) pageContext.getRequest());      
      List commonProfileList = getCommonProfileList(); // Common profile includes "reference number" and "description".
      
      List profileList = new ArrayList(Integer.parseInt(getLength()));
      if (isShowProfileAsc()) {
        profileList.addAll(defaultProfileList);        
        profileList.addAll(Integer.parseInt(getLength()) - 2, commonProfileList);
      } else {
        profileList.addAll(commonProfileList);
        profileList.addAll(defaultProfileList);
      }
      
      setCollection(profileList);
    } catch (ApplicationException ae) {
      throw new JspException("Error occur at initProfileData.", ae);
    } finally {
      docRetrievalManager.release();      
    }
  }
  
  protected List getCommonProfileList() {
    List systemProfileList = new ArrayList();
    
    DmsDefaultProfileSetting referenceNumSetting = new DmsDefaultProfileSetting();
    referenceNumSetting.setID(new Integer(1));
    referenceNumSetting.setFieldName("reference no");
    referenceNumSetting.setFieldType("S");
    referenceNumSetting.setMandatoryFlag("N");
    referenceNumSetting.setValueSuggestFlag("N");
    systemProfileList.add(referenceNumSetting);
    
    DmsDefaultProfileSetting descriptionSetting = new DmsDefaultProfileSetting();
    descriptionSetting.setID(new Integer(2));
    descriptionSetting.setFieldName("description");
    descriptionSetting.setFieldType("S");
    descriptionSetting.setMandatoryFlag("N");
    descriptionSetting.setValueSuggestFlag("N");
    systemProfileList.add(descriptionSetting);
    
    return systemProfileList;
  }
  
  /**
   * The release method, clean up resources
   *
   * @see javax.servlet.jsp.tagext.BodyTagSupport#release()
   */
  public void release() {
    super.release();
    this.documentBean = null;
    includeSystemProfile = false;
    enableDisplayFilter = false;
    showProfileAsc = true;
    defaultSelectedDisplayIDs = null;
    commonSelectedDisplayIDs = null;
    isSkipCurrentBody = false;
  }

}
